package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
	"webapp/service"
	"webapp/utils"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello world", r.URL.Path)
}

func cors(f http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Access-Control-Allow-Origin", "*")                                                     // 可将将 * 替换为指定的域名
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization") //你想放行的header也可以在后面自行添加
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")                                   //我自己只使用 get post 所以只放行它
		//w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		// 放行所有OPTIONS方法
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		// 处理请求
		f(w, r)
	}
}

func main() {
	utils.InitLog()
	log.Println("sever started")
	service.Token = make(map[string]string)
	//service.Token["12345"] = "hahaha" // for test

	http.HandleFunc("/", handler)
	http.HandleFunc("/user/login", cors(service.LoginService))
	http.HandleFunc("/user/register", cors(service.RegisterService))
	http.HandleFunc("/user/logout", cors(service.LogoutService))
	http.HandleFunc("/user/manage/userlist", cors(service.GetUserListService))
	http.HandleFunc("/user/manage/toggleManager", cors(service.ToggleManagerService))
	http.HandleFunc("/user/manage/delete", cors(service.DeleteUserService))
	http.HandleFunc("/hardwares/categories", cors(service.GetHardWareClassListService))
	http.HandleFunc("/hardwares/categories/add", cors(service.AddHardWareClassService))
	http.HandleFunc("/hardwares/categories/delete", cors(service.DeleteHardWareClassService))
	http.HandleFunc("/hardwares/categories/modify", cors(service.ModifyHardWareClassNameService))
	http.HandleFunc("/hardwares/items", cors(service.GetHardWareItemListService))
	http.HandleFunc("/hardwares/items/add", cors(service.AddHardWareItemService))
	http.HandleFunc("/hardwares/items/delete", cors(service.DeleteHardWareItemService))
	http.HandleFunc("/hardwares/items/modify", cors(service.ModifyHardwareItemService))
	http.HandleFunc("/hardwares/items/attr/modify", cors(service.ModifyHardwareItemAttrService))
	http.HandleFunc("/hardwares/items/attr/add", cors(service.AddHardWareItemAttrService))
	http.HandleFunc("/hardwares/items/attr/delete", cors(service.DeleteHardWareItemAttrService))

	//myHandler := MyHandler{}
	//http.Handle("/", &myHandler)

	server := http.Server{
		Addr: ":8080",
		//Handler:     &myHandler,
		ReadTimeout: 2 * time.Second,
	}
	err := server.ListenAndServe()
	if err != nil {
		fmt.Printf("shit")
	}

	//创建端口
	//http.ListenAndServe(":8080", nil)

}
